/**
 * Filename: AlbumWallAdapter.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/8 15:20
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.activity.YunAlbumActivity;
import com.github.postsanf.yinian.activity.YunAlbumActivity2;
import com.github.postsanf.yinian.activity.YunAlbumActivity3;
import com.github.postsanf.yinian.bean.RepaceImg;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class YunAlbumWallAdapter3 extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Activity activity;
    private Context context;
    private List<YNPhoto> datas;
    private List<RepaceImg> repaceImgs = new ArrayList<>();
    private ProgressDialog mProgressDialog;
    private boolean flag;
    private int limit;
    public YunAlbumWallAdapter3(Context context, List<YNPhoto> datas, Activity activity,Boolean flag) {
        this.context = context;
        this.datas = datas;
        this.activity = activity;
        this.flag=flag;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout ll_item_album_wall;                                    //列表View
        SimpleDraweeView iv_album_grid_item_image;                            //照片墙图片
        ImageView mSelect;

        public ViewHolder(final View itemView) {
            super(itemView);
            ll_item_album_wall = (RelativeLayout) itemView
                    .findViewById(R.id.iv_album_grid_item);
            iv_album_grid_item_image = (SimpleDraweeView) itemView
                    .findViewById(R.id.iv_album_grid_item_image);
            mSelect = (ImageView) itemView
                    .findViewById(R.id.id_item_select);

            itemView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    ViewGroup.LayoutParams vlp = itemView.getLayoutParams();
                    vlp.height = itemView.getMeasuredWidth();
                    vlp.width = itemView.getMeasuredWidth();
                    itemView.setLayoutParams(vlp);
                    return true;
                }
            });
        }

        public void bindData(final YNPhoto listItems, final int position) {
            if (listItems != null) {
                final String item = listItems.getUrl();
                if(SelectedImg.choosepic.contains(item)){
                    mSelect.setImageResource(R.drawable.pictures_selected);
                }else{
                    mSelect.setImageResource(R.drawable.picture_unselected);
                }
                final String paths = YNUrlHelper.getWallUrl(context, listItems.getThumbnail());
//                Log.d("yuhao", "listItems.getThumbnail()="+paths);
                Uri uri = Uri.parse(StringUtils.repaceImgUrl(paths));
//                Log.d("yuhao", "StringUtils.repaceImgUrl(paths)="+StringUtils.repaceImgUrl(paths));
                ImageOptHelper.showFrescoImg(uri, iv_album_grid_item_image, context);
                iv_album_grid_item_image.setOnClickListener(new View.OnClickListener() {
                    //选择，则将图片变暗，反之则反之
                    @Override
                    public void onClick(View v) {
                        if (flag){
                            limit=1;
                        }else{
                            limit=16;
                        }
                        if (SelectedImg.mSelectedImage.size() < limit) {
                            if (SelectedImg.mSelectedImage.contains(item)) {
                                // 已经选择过该图片
                                for (int i = 0; i < repaceImgs.size(); i++) {
                                    RepaceImg repaceImg = repaceImgs.get(i);
                                    if (repaceImg.getPosition() == position) {
                                        repaceImg.setScale(false);
                                    }
                                }
                                SelectedImg.mSelectedImage.remove(item);
                                SelectedImg.choosepic.remove(item);
                                SelectedImg.seleBitmap.remove(item);

                                mSelect.setImageResource(R.drawable.picture_unselected);
                                iv_album_grid_item_image.setColorFilter(null);
                            } else {
                                // 未选择该图片
                                RepaceImg repaceImg = new RepaceImg();
                                repaceImg.setPosition(position);
                                repaceImg.setScale(true);
                                repaceImgs.add(repaceImg);
                                mSelect.setImageResource(R.drawable.pictures_selected);
                                iv_album_grid_item_image.setColorFilter(Color.parseColor("#33000000"));
                                getLocalPath(item,mSelect,position);
                                SelectedImg.mSelectedImage.add(item);
                                SelectedImg.choosepic.add(item);
                            }
                        } else if (SelectedImg.mSelectedImage.size() >= limit) {
                            if (SelectedImg.mSelectedImage.contains(item)) {
                                SelectedImg.mSelectedImage.remove(item);
                                mSelect.setImageResource(R.drawable.picture_unselected);
                                iv_album_grid_item_image.setColorFilter(null);
                            }
                        }
                        if (MainActivity.goodsid == 1||MainActivity.goodsid==99) {
                            ((YunAlbumActivity) activity).setSureCount(SelectedImg.mSelectedImage.size());
                        } else if (MainActivity.goodsid == 2) {
                            ((YunAlbumActivity3) activity).setSureCount(SelectedImg.mSelectedImage.size());
                        } else if (MainActivity.goodsid == 3 || MainActivity.goodsid == 4) {
                            ((YunAlbumActivity2) activity).setSureCount(SelectedImg.mSelectedImage.size());
                        }
                    }
                });
            }
        }
    }

    String localPath;
    private void getLocalPath(final String path, final ImageView view, final int position){
        Log.d("yuhao", "getLocalPath="+position);
        mProgressDialog = ProgressDialog.show(context, "", CommonConstants.TIP_LOAD_DATA);
        Long tsLong = System.currentTimeMillis() / 1000;
        final String ts = "yn_" + tsLong.toString() + ".png";
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url1 = new URL(path);
                    // 打开链接
                    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();

                        localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yinian/YiNian" + ts;
                        File f = new File(new File(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/", "yinian/YiNian" + ts);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                        Message message = new Message();
                        message.obj=path;
                        message.what=2;
                        downloadHandler.sendMessage(message);

                        BitmapFactory.Options newOpts = new BitmapFactory.Options();
                        newOpts.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(localPath, newOpts);
                        int width = newOpts.outWidth;
                        int length = newOpts.outHeight;
                        if (!(width > 500 && length > 500)) {
                            Message message1 = new Message();
                            message1.obj=view;
                            message1.what=1;
                            updateViewHandler.sendMessage(message1);
                        }
                    }else{
                        mProgressDialog.dismiss();
                        SelectedImg.mSelectedImage.remove(path);
                        SelectedImg.choosepic.remove(path);
                        ((YunAlbumActivity3) activity).setSureCount(SelectedImg.mSelectedImage.size());
                        Message message1 = new Message();
                        message1.obj=view;
                        message1.what=1;
                        updateViewHandler.sendMessage(message1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    Handler downloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                mProgressDialog.dismiss();
                String netPath = (String) msg.obj;
                BitmapFactory.Options newOpts = new BitmapFactory.Options();
                newOpts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(localPath, newOpts);
                int width = newOpts.outWidth;
                int length = newOpts.outHeight;
                if (width > 500 && length > 500) {
                    SelectedImg.seleBitmap.put(netPath,localPath);
                }else{
                    SelectedImg.mSelectedImage.remove(netPath);
                    SelectedImg.choosepic.remove(netPath);
                    ((YunAlbumActivity3) activity).setSureCount(SelectedImg.mSelectedImage.size());
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setMessage("为了保证照片打印的质量，尺寸小于500*500px的图片不能被选择！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.create().show();
                }
            }
        }
    };

    Handler updateViewHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==1){
                ImageView view = ((ImageView) msg.obj);
                view.setImageResource(R.drawable.picture_unselected);
            }
            super.handleMessage(msg);
        }
    };
    private YNPhoto getItem(int position) {
        return datas.get(position);
    }

    // 创建ViewHolder
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.yn_yunalbum_select_item, parent, false);
        return new ViewHolder(convertView);
    }

    // 绑定数据到View
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder rv_holder, int position) {
        if (rv_holder instanceof ViewHolder) {
            final ViewHolder holder = (ViewHolder) rv_holder;
            YNPhoto listItems = getItem(position);
            holder.bindData(listItems, position);
            holder.itemView.setTag(listItems);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    public int getIdByDirection(boolean isTop) {
        if (isTop) {
            if (datas.size() <= 0) {
                return 0;
            }
            return datas.get(0).getPid();
        } else {
            return datas.get(datas.size() - 1).getPid();
        }
    }

    public void addItemsFromBottom(List<YNPhoto> items) {
        if (items == null)
            return;
        this.datas.addAll(datas.size(), items);
        this.notifyItemRangeInserted(datas.size(), items.size());
    }

    public void addItemsFromTop(List<YNPhoto> items) {
        if (items == null)
            return;
        this.datas.addAll(0, items);
        this.notifyItemRangeInserted(0, items.size());
    }
}
